/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package trab_sd;

import java.io.*;
import java.util.*;
import java.net.*;

/**
 *
 * @author moacirnq
 */
public class FileReceiver implements Runnable{
	private File file;
	private FileOutputStream fout;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	private Socket connection;
	private String fname, fpath;
	private User localUser;
	private long fsize;
	private boolean cont;
	
	public FileReceiver ( String fPath, String fName, long fSize, ObjectOutputStream out, ObjectInputStream in, Socket connection, User localUser) {
		try {
			//Guarda as informacoes do arquivo
			fname = fName;
			fsize = fSize;
			fpath = fPath;
			//tenta abrir o arquivo
			file = new File(fpath + fname);
			
			//salva a conexao
			this.connection = connection;
			this.out = out;
			this.in = in;
			
			//salva as informacoes do usuario
			this.localUser = localUser;
			cont = connection.isConnected();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void run () {
		try {
			if (cont == false) return;
			if ( file.exists() ) {
				System.out.println("O arquivo requisitado ja existe no host local.");
				out.writeUTF("NotOK");
				out.flush();
				return;
			}
			
			File tmp = File.createTempFile(fname, "" );
			
			//tenta enviar uma confirmacao de pedido
			out.writeUTF("OK");
			out.flush();
			
			//cria o arquivo
			file.createNewFile();
			
			//pega o outputstream do arquivo
			fout = new FileOutputStream(tmp);
			
			//recebe o arquivo
			System.out.println("FileReceiver: Comecando recepcao de arquivo " + fname);
			byte [] buffer = new byte [(int) fsize ];
			
			for( int i = 0; i < buffer.length; i++ ) {
				buffer[i] = in.readByte();
			}
			fout.write(buffer);
			fout.flush();
			fout.close();
			
			FileSender.copyFile(tmp, file);
			
			System.out.println("FileSender: Arquivo " + fname + " recebido");
		}
		catch ( ConnectException ce) {
			String offHost = connection.getInetAddress().getHostName();
			UserID offUser = localUser.getUserList().getByName(offHost);
			OfflineUserMsg of = new OfflineUserMsg( offUser, localUser.getServerID());
			of.run();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				connection.close();
				out.close();
				in.close();
			}
			catch (Exception ex) {
				ex.printStackTrace();
			}
			return;
		}
	}
	
}
